$(function(){
  var MyModel = Backbone.Model.extend({
    initialize:function(){
      if(!this.get("body")) {
        this.set({"body":"new document..."});
      }
    },
    clear: function(){
      this.destroy();
      this.view.remove();
    }

  });

  var MyModels = Backbone.Collection.extend({
    model: MyModel,
    url: "api"
  });

  var my_models = new MyModels;

  var MyModelView = Backbone.View.extend({
    tagName: "div",
    template: _.template($("#myModelsTmpl").html()),

    events: {
      "click .delete" : "clear",
      "blur .body" : "update"
    },

    initialize: function(){
      _.bindAll(this, 'render');
      this.model.bind('change', this.render);
      this.model.view = this;
    },

    render: function(){
      $(this.el).html(this.template(this.model.toJSON()));
      return this;
    },

    remove: function(){
      $(this.el).remove();
    },

    clear: function(){
      this.model.clear();
    },

    update: function(e){
      this.model.save({body: this.$(".body").html()});
    }
  });

  var MyAppView = Backbone.View.extend({
    el: $("#wrapper"),
    events: {
      "click #btnNew": "create"
    },

    initialize: function(){
      _.bindAll(this, 'addOne', 'addAll');

      my_models.bind('add', this.addOne);
      my_models.bind('refresh', this.addAll);

      my_models.fetch();
    },

    create: function(){
      my_models.create();
    },

    addOne: function(model){
      var view = new MyModelView({model: model});
      this.$("#bodies").append(view.render().el);
    },
    addAll: function(){
      my_models.each(this.addOne);
    }
  });

  var app = new MyAppView;
});
